package com.project;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/TicketCollectionServlet")
public class TicketCollectionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String selectedTicketData = request.getParameter("selectedTicketData");
        if (selectedTicketData != null) {
            List<String> ticketInfo = new ArrayList<>(Arrays.asList(selectedTicketData.substring(1, selectedTicketData.length() - 1).split("\",\"")));
            ticketInfo.replaceAll(item -> item.replace("\"", ""));

            if (ticketInfo.size() >= 4) {
                // 构造请求信息（包含唯一ID）
                Map<String, String> requestMap = new HashMap<>();
                requestMap.put("id", UUID.randomUUID().toString());  // 生成唯一请求ID
                requestMap.put("ticketId", ticketInfo.get(0));
                requestMap.put("oid", ticketInfo.get(1));
                requestMap.put("uid", ticketInfo.get(2));
                requestMap.put("seat", ticketInfo.get(3));
                requestMap.put("state", "0");  // 初始状态：待审核

                // 获取或初始化ServletContext中的待审核列表
                List<Map<String, String>> pendingRequests = (List<Map<String, String>>) getServletContext().getAttribute("pendingTicketRequests");
                if (pendingRequests == null) {
                    pendingRequests = new ArrayList<>();
                }
                pendingRequests.add(requestMap);
                getServletContext().setAttribute("pendingTicketRequests", pendingRequests);  // 保存到全局上下文

                request.setAttribute("success", true);
            }
        }
        request.getRequestDispatcher("ticketCollection.jsp").forward(request, response);
    }
}